package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.Announcement;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Contacts;
import com.tanhua.server.vo.MessageAnnouncement;
import com.tanhua.server.vo.MessageLike;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class IMService {

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String url;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 添加好友
     *
     * @param userId 朋友id
     */
    public boolean contactUser(Long userId) {
        User user = UserThreadLocal.get();

        Users users = new Users();
        users.setUserId(user.getId());
        users.setFriendId(userId);
        //将数据保存到mongoDB中,而且存两个表(两个用户成为朋友需要两张表)
        this.usersApi.saveUsers(users);

        //注册好友关系到环信
        //环信所需固定格式
        String targetUrl = url + "/user/huanxin/contacts/" + users.getUserId() + "/" + users.getFriendId();
        ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, null, Void.class);
        if (responseEntity.getStatusCodeValue() == 200) {
            //当返回的状态码为200表示在环信中关系建立成功
            return true;
        }
        return false;
    }


    /**
     * 查询联系人列表
     *
     * @param page 页码
     * @param pageSize 每页大小
     * @param keyword  关键字
     * @return 列表结果对象
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        User user = UserThreadLocal.get();

        List<Users> usersList = null;
        //判断是否有关键字参与搜索
        if (StringUtils.isNotEmpty(keyword)) {
            //关键不为空，查询所有的好友,在后面进行关键字过滤
            usersList = this.usersApi.queryAllUsersList(user.getId());
        } else {
            //关键字为空，进行分页查询
            PageInfo<Users> usersPageInfo = this.usersApi.queryUsersList(user.getId(), page, pageSize);
            usersList = usersPageInfo.getRecords();
        }

        //遍历users对象集合,将friendId存入userIds集合里
        List<Long> userIds = new ArrayList<>();
        for (Users users : usersList) {
            userIds.add(users.getFriendId());
        }

        //条件:userId等于userIds集合的
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        //当关键字不为空则添加条件:昵称包含关键字的
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.like("nick_name", keyword);
        }

        //通过条件从数据库查找所有符合条件的userInfo放入集合中
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        //建立Contacts对象集合
        List<Contacts> contactsList = new ArrayList<>();

        //填充用户信息 userInfo的属性封装到Contacts中
        for (UserInfo userInfo : userInfoList) {
            Contacts contacts = new Contacts();
            //因为id不是必须的所以这里不封装
            contacts.setAge(userInfo.getAge());
            //头像
            contacts.setAvatar(userInfo.getLogo());
            //获取他的性别枚举->获取他的性别->转为小写
            contacts.setGender(userInfo.getSex().name().toLowerCase());
            contacts.setNickname(userInfo.getNickName());
            //将long类型转为String类型
            contacts.setUserId(String.valueOf(userInfo.getUserId()));
            //substringBefore截取"-"之前的
            contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));

            contactsList.add(contacts);
        }

        //将数据封装到PageResult对象中
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        //存数据的
        pageResult.setItems(contactsList);

        return pageResult;
    }




    /**
     * 查询点赞列表
     * @param page 页码
     * @param pageSize 每页显示数量
     * @return PageResult对象
     */
    public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        return this.messageCommentList(1, page, pageSize);
    }

    /**
     * 查询评论列表
     * @param page 页码
     * @param pageSize 每页显示数量
     * @return PageResult对象
     */
    public PageResult queryMessageCommentList(Integer page, Integer pageSize) {
        return this.messageCommentList(2, page, pageSize);
    }

    /**
     * 查询喜欢列表
     * @param page 页码
     * @param pageSize 每页显示数量
     * @return PageResult对象
     */
    public PageResult queryMessageLoveList(Integer page, Integer pageSize) {
        return this.messageCommentList(3, page, pageSize);
    }

    /**
     * 操作方法(因为点赞,评论,喜欢的操作差不多只是类型不一样所以抽取了该方法)
     * @param type 操作类型(1-点赞,2-评论,3-喜欢)
     * @param page 页码
     * @param pageSize 每页数量
     * @return PageResult
     */
    private PageResult messageCommentList(Integer type, Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();

        //查询pageInfo对象
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(user.getId(), type, page, pageSize);

        //封装PageResult对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);

        //获取存入的Comment对象集合
        List<Comment> records = pageInfo.getRecords();

        //当集合size=0则将null封装到pageResult对象中  并将pageResult对象返回
        if (0==records.size()){
            pageResult.setItems(null);
            return pageResult;
        }

        List<Long> userIds = new ArrayList<>();
        for (Comment comment : records) {
            userIds.add(comment.getUserId());
        }

        //通过操作(1-点赞,2-评论,3-喜欢)人的id集合,获取所有操作人的   userInfo对象集合
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        //操作列表集合
        List<MessageLike> messageLikeList = new ArrayList<>();
        //遍历Comment评论表对象 和 UserInfo用户信息对象 将值封装到MessageLike操作列表集合中
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                //两个对象的用户id要一样
                if(userInfo.getUserId().longValue() == record.getUserId().longValue()){

                    MessageLike messageLike = new MessageLike();
                    messageLike.setId(record.getId().toHexString());
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setNickname(userInfo.getNickName());
                    messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

                    messageLikeList.add(messageLike);
                    break;
                }
            }
        }

        //将数据封装到pageResult对象中
        pageResult.setItems(messageLikeList);
        return pageResult;
    }

    /**
     *查询公告列表
     * @param page 页码
     * @param pageSize 每页数量
     * @return PageResult
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        //得到分页对象
        IPage<Announcement> announcementPage = this.announcementService.queryList(page, pageSize);

        List<MessageAnnouncement> messageAnnouncementList = new ArrayList<>();

        //遍历分页对象中的数据 ,将其中的数据封装到MessageAnnouncement中,再存入集合中
        for (Announcement record : announcementPage.getRecords()) {
            MessageAnnouncement messageAnnouncement = new MessageAnnouncement();
            messageAnnouncement.setId(record.getId().toString());
            messageAnnouncement.setTitle(record.getTitle());
            messageAnnouncement.setDescription(record.getDescription());
            messageAnnouncement.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

            messageAnnouncementList.add(messageAnnouncement);
        }

        //将MessageAnnouncement对象集合封装到PageResult对象中
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(messageAnnouncementList);

        return pageResult;
    }
}
